/**
 * 路径配置
 */
var urlConfig = {
	getRoleList : baseUrl + "role/getRoleList",//角色表格的数据
	saveRole : baseUrl + "role/saveRole",
	updateRole : baseUrl + "role/updateRole",
	deleteRole : baseUrl + "role/deleteRole",
	getRoleByIdAll : baseUrl + "role/getRoleByIdAll",
	isRepeat : baseUrl + "role/isRepeat",
	getRoleFunctionList : baseUrl + "function/getRoleFunctionList"
}
var table_row_num = 10;//表格显示行数 
var selectdnodeIds = [];//树加载展开后删除已回显节点
var add_update;
var NewTreeData = [];
var Public_FontColor = "#000";
/**
 * 表格渲染
 */

$(document).ready(function() {
	//取消掉Datatables弹出的错误提示(当datatables有空数据时，不会弹出alert)
	$.fn.dataTable.ext.errMode = function(s, h, m) {
	}
	createTable();

});
function createTable() {
	$.ajax({
		url : urlConfig.getRoleList,
		type : 'post',
		async : true, // 默认为true 异步 
		dataType : "json",
		error : function() {
			console.info('error');
		},
		success : function(data) {

			tableData = data.data;
			for (var i = 0; i < tableData.length; i++) {
				tableData[i].rowNum = i + 1;
			}
			showTable(tableData);
		}
	})
}

function showTable(tableData) {
	$('#am_tab')
			.DataTable(
					{
						destroy : true,
						//paging:   false, //禁用分页
						ordering : false,
						bAutoWidth : false,
						info : false,//禁用显示条目
						searching : false,
						filter : false,//搜索框禁用
						lengthChange : false, //显示条目禁用
						displayLength : table_row_num, //显示条目
						data : tableData,
						//激活功能下拉列表 
						fnDrawCallback : function() {
							$('.am-dropdown').dropdown({
								justify : '#doc-dropdown-justify-js'
							});
						},

						columns : [ {
							data : "rowNum",
							width : 10
						}, {
							data : "roleName",
							sClass : "am-text-center"
						}, {
							data : null,
							sClass : "am-text-center"
						}, {
							"orderable" : false,
							"data" : null,
							"defaultContent" : '',
							sClass : "am-text-center"

						} ],
						"columnDefs" : [
								{
									targets : 2,
									"render" : function(data, type, full, meta) {
										var obj = data.roleId + "_Id&&"
												+ data.functionNames;

										/*return '<button class="am-btn am-btn-default am-btn-xs am-text-success" id="'+data.roleId+'_Id"  onclick="getFunctionNames(\''
										+ obj
										+ '\')"><span class="am-icon-search"></span> '
										+ '查看' + '</button>';*/

										var obj_arr = obj.split("&&")[1];
										var templateNameArray = obj_arr
												.replace(/,/g, "</br>");
										return '<div class="am-dropdown" data-am-dropdown><button class="am-btn am-btn-default am-btn-xs am-text-success am-dropdown-toggle" data-am-dropdown-toggle><span class="am-icon-search"></span> 查看</button>'
												+ '<div class="am-dropdown-content am-padding-0" style="width: 300px">'
												+ '<div class="am-padding" style="max-height:300px;overflow-y:auto;">'
												+ templateNameArray
												+ '</div>'
												+ '</div></div>';
									}

								},
								{
									targets : 3,
									"render" : function(data, type, full, meta) {

										return '<div class="am-text-center">'
												+ ' <div class="am-btn-group am-btn-group-xs">'
												+ '  <button id="'
												+ data.roleId
												+ '" onclick="showModal(this)" class="am-btn am-btn-default am-btn-xs am-text-secondary"><span class="am-icon-pencil-square-o"></span> 修改</button>'

												+ ' <button id="'
												+ data.roleId
												+ '" onclick="showConfirm(this)" class="am-btn am-btn-default am-btn-xs am-text-danger am-hide-sm-only"><span class="am-icon-trash-o"></span> 删除</button>'
												+ ' </div>' + ' </div>';
									}
								} ]
					});
}
function getTreeData(mar, arrIds) {
	if (mar == "edit") {
		//selectdnodeIds=;
		for (var i = 0; i < ((arrIds.functionIds).split(",")).length; i++) {
			selectdnodeIds.push(parseInt(((arrIds.functionIds).split(","))[i]))
		}

		$("#roleName").val(arrIds.roleName);
	}
	$
			.ajax({
				url : urlConfig.getRoleFunctionList,
				data : {},
				type : "post",
				cache : false,
				dataType : "text",
				success : function(data) {
					var sussDate = eval('(' + data + ')');

					var jsonObject1 = sussDate.data[0];
					var keys1 = [];
					for ( var p1 in jsonObject1) {//获取所有key
						if (jsonObject1.hasOwnProperty(p1))
							keys1.push(p1);
					}
					var treeData = [];

					for (var y = 0; y < keys1.length; y++) {
						for (var x = 0; x < jsonObject1[keys1[y]].length; x++) {
							jsonObject1[keys1[y]][x].type = "item";
							jsonObject1[keys1[y]][x]["title"] = jsonObject1[keys1[y]][x].text;
							jsonObject1[keys1[y]][x]["attr"] = {
								"id" : jsonObject1[keys1[y]][x].functionId
							};
						}
						var obj = {
							id : keys1[y].split("&&&")[1],
							title : keys1[y].split("&&&")[0],
							type : "folder",
							products : jsonObject1[keys1[y]],
							attr : {
								"id" : keys1[y].split("&&&")[1]
							}
						}
						treeData.push(obj);
					}
					initOptions(treeData);

				},
				error : function(sussDate) {

				}
			})

}

/**
 * 初始化下拉列表
 */
function initOptions(treeDatas) {
	NewTreeData = treeDatas;
	$(".am-tree-icon-folder").attr("style", "display:none") //树去掉加减号样式
	$("#firstTree").tree("destroy")
	var ele = $("#Treecp").clone();
	ele.attr("id", "firstTree");
	$("#TreeDiv").html(ele);
	$("#firstTree").tree(
			{
				dataSource : function(options, callback) {

					callback({
						data : options.products || treeDatas
					});

					for (var i = 0; i < selectdnodeIds.length; i++) {

						if ($("#" + selectdnodeIds[i]).html() == undefined) {

						} else {

							$("#" + selectdnodeIds[i]).find("input:first")
									.attr("checked", true);

						}
					}

					$('#firstTree .am-tree-branch .am-tree-branch-name')
							.unbind('click').click(function() {
								return false
							});//禁用树按钮点击事件

					$('#firstTree .am-tree-item .am-tree-item-name').unbind(
							'click').click(function() {
						return false
					});//禁用树按钮点击事件	

				},
				multiSelect : true, // 多选
				cacheItems : false, // 缓存
				folderSelect : true
			//文件夹被选中
			});

}

function thisNodeTreeTextColor(t) {//节点树加载

	$("#firstTree  .am-tree-label").unbind('click').click(function() {
		return false
	});//禁用树按钮点击事件
	var nodeIdSplit = parseInt($(t).attr("id"));

	//被选中树id
	if ($(t).find(".checkboxClass").attr("checked")) {
		if (add_update == "edituserButId") {//编辑用户

			selectdnodeIds.splice($.inArray(nodeIdSplit, selectdnodeIds), 1);//勾选取消删除数组中的id
			$(t).find(".checkboxClass").removeAttr("checked");

		} else {
			selectdnodeIds.splice($.inArray(nodeIdSplit, selectdnodeIds), 1);//勾选取消删除数组中的id
			$(t).find(".checkboxClass").removeAttr("checked");
		}

		if ($(t).hasClass("am-tree-selected")) {
			$(t).find(".am-tree-item-name .am-tree-label").css("color",
					Public_FontColor);
		} else {
			$(t).find(".am-tree-item-name .am-tree-label").css("color",
					"rgb(8,8,8)");
		}
	} else {

		if (add_update == "edituserButId") {//编辑用户

			selectdnodeIds.push(nodeIdSplit);//勾选选中添加数组中的id
			$(t).find(".checkboxClass").attr("checked", true);
			$(t).find(".checkboxClass").prop("checked", true);

		} else {
			selectdnodeIds.push(nodeIdSplit);//勾选选中添加数组中的id
			$(t).find(".checkboxClass").attr("checked", true);
			$(t).find(".checkboxClass").prop("checked", true);
		}
		if ($(t).hasClass("am-tree-selected")) {
			$(t).find(".am-tree-item-name .am-tree-label").css("color",
					Public_FontColor);
		} else {
			$(t).find(".am-tree-item-name .am-tree-label").css("color",
					"rgb(8,8,8)");

		}

	}

	selectdnodeIds = arr(selectdnodeIds);

}

function getchilanodeId(nid) {//根据父节点获取子节点id

	var ids = [];
	for (var i = 0; i < NewTreeData.length; i++) {
		if (NewTreeData[i].id == nid) {
			for (var y = 0; y < (NewTreeData[i].products).length; y++) {
				ids.push(NewTreeData[i].products[y].functionId);
			}
		}
	}
	return ids;
}

function getParentnodeId(nid) {//根据子节点获取父节点id
	console.info(NewTreeData)
	console.info(nid)
	var ids = [];
	for (var t = 0; t < nid.length; t++) {

		for (var i = 0; i < NewTreeData.length; i++) {

			for (var y = 0; y < (NewTreeData[i].products).length; y++) {
				if (NewTreeData[i].products[y].functionId == nid[t]) {
					ids
							.push(nid[t] + "_"
									+ NewTreeData[i].products[y].parentId);
				}

			}

		}
	}
	return ids;
}

function checkboxClick(t) {//判断节点树是否被勾选

	var clickMarkVar = $(t).parents("li:first").hasClass("am-tree-branch");

	if (clickMarkVar == true) {//如果是父节点
		var nodeIdSplit = $(t).parents("li:first").attr("id");
		var ids = getchilanodeId(nodeIdSplit);

		//被选中树id
		if ($(t).attr("checked")) {
			if (add_update == "edituserButId") {//编辑用户

				for (var i = 0; i < ids.length; i++) {
					selectdnodeIds.splice($.inArray(ids[i], selectdnodeIds), 1);//勾选取消删除数组中的id
				}
				//selectdnodeIds.splice($.inArray(nodeIdSplit,selectdnodeIds),1);//勾选取消删除数组中的id
				$(t).removeAttr("checked");

			} else {
				for (var i = 0; i < ids.length; i++) {
					selectdnodeIds.splice($.inArray(ids[i], selectdnodeIds), 1);//勾选取消删除数组中的id
				}
				//selectdnodeIds.splice($.inArray(nodeIdSplit,selectdnodeIds),1);//勾选取消删除数组中的id
				$(t).removeAttr("checked");
			}
		} else {

			if (add_update == "edituserButId") {//编辑用户

				for (var i = 0; i < ids.length; i++) {
					selectdnodeIds.push(ids[i]);//勾选选中添加数组中的id
				}
				$(t).attr("checked", true);

			} else {
				for (var i = 0; i < ids.length; i++) {
					selectdnodeIds.push(ids[i]);//勾选选中添加数组中的id
				}
				$(t).attr("checked", true);
			}
		}

		selectdnodeIds = arr(selectdnodeIds);

	}
}

/**
 * 添加或修改的模态窗口
 * type=1 添加
 * type=2 修改
 */
function showModal(t) {
	var $modal = $("#am_modal");
	var $title = $("#am_modal_title");
	var modal_width = 900;
	var modal_height = 600;
	selectdnodeIds = [];
	if (t != undefined) {
		$title.text("修改");
		add_update = "edituserButId";
		$modal.attr("type", 2);
		var id = $(t).attr("id");
		$("#roleId").val(id);
		var data = {
			roleId : id
		};
		$.ajax({
			url : urlConfig.getRoleByIdAll,
			data : data,
			type : "post",
			cache : false,
			dataType : "text",
			success : function(data) {
				var sussDate = eval('(' + data + ')');

				getTreeData("edit", sussDate);
			},
			error : function(sussDate) {

			}
		})

	} else {
		getTreeData("add", "0");
		add_update = "adduserButId";
		$title.text("添加");
		$modal.attr("type", 1);
		$("#roleName").val("");

	}
	$modal.modal({
		width : modal_width,
		height : modal_height
	});

}
/**
 * 删除信息
 */
function showConfirm(t) {
	var $modal = $("#am_confirm");
	var id = $(t).attr("id");
	$("#roleId").val(id);
	$modal.modal({
		relatedTarget : this,
		onConfirm : function(options) {
			var id = $("#roleId").val();
			var data = {
				roleId : id
			};
			var config = {
				url : urlConfig.deleteRole,
				data : data,
				callback : callbackFun
			};
			jqAjax(config);
		},
		onCancel : function() {
		}
	});
}
/**
 * 提交表单
 */
function commitModal() {
	var $modal = $("#am_modal");
	if ($modal.attr("type") == 1) {
		var roleName = $("#roleName").val();
		var roleData = {
			roleName : roleName
		};
		var callbackRole = function back(data) {
			if (data == '0') {//用户名可以用
				var data = {

					roleId : "",
					parentId : "",
					roleName : roleName,
					functionIds : (getParentnodeId(selectdnodeIds)).join(",")
				};
				var config = {
					url : urlConfig.saveRole,
					data : data,
					callback : callbackFun
				};
				if (validatorole()) {
					jqAjax(config);
				}
			} else {
				alert("角色已存在,不能提交！")
			}
		}
		var configRole = {
			url : urlConfig.isRepeat,
			data : roleData,
			callback : callbackRole
		};
		jqAjax(configRole)
	}
	if ($modal.attr("type") == 2) {
		var roleName = $("#roleName").val();
		var data = {

			roleId : $("#roleId").val(),
			parentId : "",
			roleName : roleName,
			functionIds : (getParentnodeId(selectdnodeIds)).join(",")
		};
		var config = {
			url : urlConfig.updateRole,
			data : data,
			callback : callbackFun
		};

		if (validatorole()) {
			jqAjax(config);
		}
	}
}
/**
 * 表单验证
 * @returns
 */
function validatorole() {
	var roleName = $("#roleName").val();
	if (roleName == undefined || roleName == '') {
		alert("角色名不能为空");
		return false;
	}
	var functionIds = (getParentnodeId(selectdnodeIds)).join(",");
	console.info(functionIds)
	if (functionIds == undefined || functionIds == '') {
		alert("角色功能不能为空");
		return false;
	}
	return true;
}

/**
 *  判断重复
 * @param roleName
 * @returns
 */
function Repeat(roleName) {
	var data = {
		roleName : roleName
	};
	var callback = function back(data) {
		return data;
	}
	var config = {
		url : urlConfig.isRepeat,
		data : data,
		callback : callback
	};
	jqAjax(config);
}
function callbackFun(data) {
	createTable();
	showAlertMsg(data.msg, "am_modal");
}

/**
 * 查看详情
 * @param names
 * @returns
 */
function getFunctionNames(names) {
	var id = names.split("&&")[0];
	var value = names.split("&&")[1];
	warning(id, value);

}
